"use client";

import { useState, useEffect } from "react";
import {
  FiFileText,
  FiUsers,
  FiSettings,
  FiClock,
  FiLogOut,
  FiPieChart,
  FiBarChart2,
} from "react-icons/fi";
import { motion } from "framer-motion";
import { useRouter } from "next/navigation";
import {
  Chart as ChartJS,
  ArcElement,
  Tooltip,
  Legend,
  CategoryScale,
  LinearScale,
  BarElement,
  Title,
} from "chart.js";
import { Pie, Bar } from "react-chartjs-2";

// 注册Chart.js组件
ChartJS.register(
  ArcElement,
  Tooltip,
  Legend,
  CategoryScale,
  LinearScale,
  BarElement,
  Title
);

// 模拟数据，实际使用时应该从API获取
const mockRecentDocs = [
  { id: 1, title: "系统设计文档", author: "张三", updatedAt: "2023-10-15" },
  { id: 2, title: "用户手册", author: "李四", updatedAt: "2023-10-14" },
  { id: 3, title: "API文档", author: "王五", updatedAt: "2023-10-13" },
  { id: 4, title: "产品规划", author: "赵六", updatedAt: "2023-10-12" },
];

// 添加模拟用户角色数据
const mockUserRoles = {
  labels: ["管理员", "编辑者", "查看者", "贡献者"],
  datasets: [
    {
      label: "用户角色分布",
      data: [8, 25, 35, 10],
      backgroundColor: [
        "rgba(255, 99, 132, 0.6)",
        "rgba(54, 162, 235, 0.6)",
        "rgba(255, 206, 86, 0.6)",
        "rgba(75, 192, 192, 0.6)",
      ],
      borderColor: [
        "rgba(255, 99, 132, 1)",
        "rgba(54, 162, 235, 1)",
        "rgba(255, 206, 86, 1)",
        "rgba(75, 192, 192, 1)",
      ],
      borderWidth: 1,
    },
  ],
};

// 添加模拟文档类型数据
const mockDocTypes = {
  labels: ["技术文档", "产品规划", "用户手册", "API文档", "会议记录", "其他"],
  datasets: [
    {
      label: "文档类型分布",
      data: [350, 275, 220, 180, 125, 100],
      backgroundColor: [
        "rgba(255, 99, 132, 0.7)",
        "rgba(54, 162, 235, 0.7)",
        "rgba(255, 206, 86, 0.7)",
        "rgba(75, 192, 192, 0.7)",
        "rgba(153, 102, 255, 0.7)",
        "rgba(255, 159, 64, 0.7)",
      ],
      borderColor: [
        "rgba(255, 99, 132, 1)",
        "rgba(54, 162, 235, 1)",
        "rgba(255, 206, 86, 1)",
        "rgba(75, 192, 192, 1)",
        "rgba(153, 102, 255, 1)",
        "rgba(255, 159, 64, 1)",
      ],
      borderWidth: 1,
    },
  ],
};

export default function HomePage() {
  const router = useRouter();
  const [stats, setStats] = useState({
    totalDocs: 0,
    totalUsers: 0,
    recentDocs: [],
  });

  const [isLoading, setIsLoading] = useState(true);

  useEffect(() => {
    // 检查登录状态
    const isLoggedIn = localStorage.getItem("isLoggedIn");
    if (!isLoggedIn) {
      router.push("/login");
      return;
    }

    // 模拟API加载数据
    setTimeout(() => {
      setStats({
        totalDocs: 1250,
        totalUsers: 78,
        recentDocs: mockRecentDocs,
      });
      setIsLoading(false);
    }, 1000);

    // 实际项目中应使用以下方式从API获取数据
    // async function fetchData() {
    //   try {
    //     const [docsResponse, usersResponse, recentDocsResponse] = await Promise.all([
    //       fetch('/api/stats/documents'),
    //       fetch('/api/stats/users'),
    //       fetch('/api/documents/recent')
    //     ]);
    //
    //     const docsData = await docsResponse.json();
    //     const usersData = await usersResponse.json();
    //     const recentDocsData = await recentDocsResponse.json();
    //
    //     setStats({
    //       totalDocs: docsData.count,
    //       totalUsers: usersData.count,
    //       recentDocs: recentDocsData
    //     });
    //   } catch (error) {
    //     console.error('获取数据失败:', error);
    //   } finally {
    //     setIsLoading(false);
    //   }
    // }
    //
    // fetchData();
  }, [router]);

  const handleLogout = () => {
    localStorage.removeItem("isLoggedIn");
    router.push("/login");
  };

  const fadeIn = {
    hidden: { opacity: 0, y: 20 },
    visible: { opacity: 1, y: 0 },
  };

  if (isLoading) {
    return (
      <div className='flex justify-center items-center h-[80vh]'>
        <div className='animate-spin rounded-full h-16 w-16 border-t-2 border-b-2 border-blue-500'></div>
      </div>
    );
  }

  return (
    <div className='container mx-auto px-4 py-8'>
      {/* 顶部导航栏 */}

      {/* 欢迎标语 */}
      <motion.div
        className='text-center mb-12'
        initial='hidden'
        animate='visible'
        variants={fadeIn}
        transition={{ duration: 0.5 }}
      >
        <h1 className='text-4xl font-bold bg-gradient-to-r from-blue-500 to-purple-600 text-transparent bg-clip-text mb-4'>
          欢迎使用雅典娜知识库
        </h1>
        <p className='text-lg text-gray-600 dark:text-gray-300'>
          企业级知识管理系统，集中存储和管理您的团队知识
        </p>
      </motion.div>

      {/* 数据统计卡片 */}
      <motion.div
        className='grid grid-cols-1 md:grid-cols-2 gap-6 mb-12'
        initial='hidden'
        animate='visible'
        variants={fadeIn}
        transition={{ duration: 0.5, delay: 0.2 }}
      >
        <div className='bg-gradient-to-br from-blue-50 to-blue-100 dark:from-blue-900/30 dark:to-purple-900/30 p-6 rounded-xl shadow-sm border border-blue-200 dark:border-blue-800 backdrop-blur-sm'>
          <div
            className='flex items-center mb-4 click_active'
            onClick={() => router.push("/documents")}
          >
            <div className='bg-blue-500 p-3 rounded-lg text-white mr-4'>
              <FiFileText size={24} />
            </div>
            <div>
              <h2 className='text-2xl font-bold text-blue-700 dark:text-blue-300'>
                {stats.totalDocs}
              </h2>
              <p className='text-blue-600 dark:text-blue-400'>文档总数</p>
            </div>
          </div>
          <p className='text-sm text-gray-600 dark:text-gray-400'>
            所有团队成员共享的知识文档总量
          </p>
        </div>

        <div className='bg-gradient-to-br from-purple-50 to-purple-100 dark:from-purple-900/30 dark:to-blue-900/30 p-6 rounded-xl shadow-sm border border-purple-200 dark:border-purple-800 backdrop-blur-sm'>
          <div
            className='flex items-center mb-4 click_active'
            onClick={() => router.push("/users")}
          >
            <div className='bg-purple-500 p-3 rounded-lg text-white mr-4'>
              <FiUsers size={24} />
            </div>
            <div>
              <h2 className='text-2xl font-bold text-purple-700 dark:text-purple-300'>
                {stats.totalUsers}
              </h2>
              <p className='text-purple-600 dark:text-purple-400'>用户总数</p>
            </div>
          </div>
          <p className='text-sm text-gray-600 dark:text-gray-400'>
            当前系统的活跃用户数量
          </p>
        </div>
      </motion.div>

      {/* 最近更新和权限配置 */}
      <div className='grid grid-cols-1 lg:grid-cols-3 gap-8'>
        {/* 最近更新文档 */}
        <motion.div
          className='lg:col-span-2 bg-white dark:bg-gray-800 rounded-xl shadow-sm border border-gray-200 dark:border-gray-700'
          initial='hidden'
          animate='visible'
          variants={fadeIn}
          transition={{ duration: 0.5, delay: 0.4 }}
        >
          <div className='border-b border-gray-200 dark:border-gray-700 p-4 flex items-center'>
            <FiClock className='text-blue-500 mr-2' />
            <h2 className='text-xl font-semibold'>最近更新文档</h2>
          </div>
          <div className='p-4'>
            <div className='overflow-x-auto'>
              <table className='min-w-full'>
                <thead>
                  <tr className='text-left text-gray-500 dark:text-gray-400 text-sm'>
                    <th className='pb-2'>文档名称</th>
                    <th className='pb-2'>更新人</th>
                    <th className='pb-2'>更新时间</th>
                  </tr>
                </thead>
                <tbody>
                  {stats.recentDocs.map((doc) => (
                    <tr
                      key={doc.id}
                      className='border-t border-gray-100 dark:border-gray-700 hover:bg-gray-50 dark:hover:bg-gray-750'
                    >
                      <td className='py-3 text-blue-600 dark:text-blue-400 font-medium'>
                        <a
                          href={`/documents/${doc.id}`}
                          className='hover:underline'
                        >
                          {doc.title}
                        </a>
                      </td>
                      <td className='py-3 text-gray-600 dark:text-gray-300'>
                        {doc.author}
                      </td>
                      <td className='py-3 text-gray-500 dark:text-gray-400'>
                        {doc.updatedAt}
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
            <div className='mt-4 text-right'>
              <a
                href='/documents'
                className='text-blue-500 hover:text-blue-600 dark:hover:text-blue-400 text-sm font-medium'
              >
                查看所有文档 →
              </a>
            </div>
          </div>
        </motion.div>

        {/* 权限配置入口 */}
        <motion.div
          className='bg-white dark:bg-gray-800 rounded-xl shadow-sm border border-gray-200 dark:border-gray-700'
          initial='hidden'
          animate='visible'
          variants={fadeIn}
          transition={{ duration: 0.5, delay: 0.6 }}
        >
          <div className='border-b border-gray-200 dark:border-gray-700 p-4 flex items-center'>
            <FiSettings className='text-purple-500 mr-2' />
            <h2 className='text-xl font-semibold'>系统管理</h2>
          </div>
          <div className='p-4 space-y-4'>
            <a
              href='/permissions'
              className='flex items-center p-3 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-750 transition-colors duration-150'
            >
              <div className='bg-blue-100 dark:bg-blue-900/30 p-2 rounded-md text-blue-500 mr-3'>
                <FiUsers size={20} />
              </div>
              <div>
                <h3 className='font-medium'>权限配置</h3>
                <p className='text-sm text-gray-500 dark:text-gray-400'>
                  管理用户访问权限
                </p>
              </div>
            </a>

            <a
              href='/documents/tags'
              className='flex items-center p-3 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-750 transition-colors duration-150'
            >
              <div className='bg-purple-100 dark:bg-purple-900/30 p-2 rounded-md text-purple-500 mr-3'>
                <FiFileText size={20} />
              </div>
              <div>
                <h3 className='font-medium'>文档标签管理</h3>
                <p className='text-sm text-gray-500 dark:text-gray-400'>
                  管理分档分类
                </p>
              </div>
            </a>

            <a
              href='/system'
              className='flex items-center p-3 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-750 transition-colors duration-150'
            >
              <div className='bg-gray-100 dark:bg-gray-700 p-2 rounded-md text-gray-500 dark:text-gray-400 mr-3'>
                <FiSettings size={20} />
              </div>
              <div>
                <h3 className='font-medium'>系统设置</h3>
                <p className='text-sm text-gray-500 dark:text-gray-400'>
                  系统基础配置
                </p>
              </div>
            </a>
          </div>
        </motion.div>

        {/* 在这里添加统计图表部分，放在最近更新文档和系统管理的下方 */}
        <motion.div
          className='lg:col-span-3 mt-8 grid grid-cols-1 md:grid-cols-2 gap-8'
          initial='hidden'
          animate='visible'
          variants={fadeIn}
          transition={{ duration: 0.5, delay: 0.8 }}
        >
          {/* 用户角色分布饼图 */}
          <div className='bg-white dark:bg-gray-800 rounded-xl shadow-sm border border-gray-200 dark:border-gray-700'>
            <div className='border-b border-gray-200 dark:border-gray-700 p-4 flex items-center'>
              <FiPieChart className='text-blue-500 mr-2' />
              <h2 className='text-xl font-semibold'>用户角色分布</h2>
            </div>
            <div className='p-6 h-80 flex items-center justify-center'>
              <Pie
                data={mockUserRoles}
                options={{
                  responsive: true,
                  maintainAspectRatio: false,
                  plugins: {
                    legend: {
                      position: "bottom",
                      labels: {
                        font: {
                          size: 12,
                        },
                      },
                    },
                    tooltip: {
                      callbacks: {
                        label: function (context) {
                          const label = context.label || "";
                          const value = context.raw || 0;
                          const total = context.dataset.data.reduce(
                            (a, b) => a + b,
                            0
                          );
                          const percentage = Math.round((value / total) * 100);
                          return `${label}: ${value}人 (${percentage}%)`;
                        },
                      },
                    },
                  },
                }}
              />
            </div>
          </div>

          {/* 文档类型分布柱状图 */}
          <div className='bg-white dark:bg-gray-800 rounded-xl shadow-sm border border-gray-200 dark:border-gray-700'>
            <div className='border-b border-gray-200 dark:border-gray-700 p-4 flex items-center'>
              <FiBarChart2 className='text-purple-500 mr-2' />
              <h2 className='text-xl font-semibold'>文档类型分布</h2>
            </div>
            <div className='p-6 h-80 flex items-center justify-center'>
              <Bar
                data={mockDocTypes}
                options={{
                  responsive: true,
                  maintainAspectRatio: false,
                  plugins: {
                    legend: {
                      display: false,
                    },
                    tooltip: {
                      callbacks: {
                        label: function (context) {
                          const label = context.dataset.label || "";
                          const value = context.raw || 0;
                          return `${label}: ${value}份文档`;
                        },
                      },
                    },
                  },
                  scales: {
                    y: {
                      beginAtZero: true,
                    },
                    x: {},
                  },
                }}
              />
            </div>
          </div>
        </motion.div>
      </div>
    </div>
  );
}
